package ai.leinao.notify.email;

import ai.leinao.notify.core.utils.TemplateUtils;
import cn.hutool.core.bean.BeanUtil;
import ai.leinao.notify.core.template.Template;
import ai.leinao.notify.core.template.TemplateProperties;
import ai.leinao.notify.core.template.VariableDefinition;
import cn.hutool.core.collection.CollUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.*;

/**
 * 邮件模板
 *
 * @author zhong.wang
 * @date 2025/7/9
 */
@Getter
@Setter
@ToString
public class EmailTemplate implements Template {
    /**
     * 模板ID
     */
    private String templateId;

    /**
     * 主题
     */
    private String subject;

    /**
     *  内容
     */
    private String text;

    /**
     * 接收者
     */
    private String sendTo;

    /**
     * 变量池
     */
    private Map<String, VariableDefinition> variables;


    /**
     * 创建邮件模板
     * @param templateProperties
     * @return
     */
    public EmailTemplate of(TemplateProperties templateProperties) {
        if(CollUtil.isEmpty(variables)){
            variables = new HashMap<>();
        }
        BeanUtil.copyProperties(templateProperties.getTemplate(), this);
        this.templateId = templateProperties.getId();
        //动态配置的变量
        if (null != templateProperties.getVariableDefinitions()) {
            for (VariableDefinition embeddedVariable : templateProperties.getVariableDefinitions()) {
                this.variables.put(embeddedVariable.getId(), embeddedVariable);
            }
        }
        return this;
    }

    /**
     * 赋值
     * @param context
     */
    @Override
    public void renderVariable(Map<String, Object> context){
        this.sendTo = TemplateUtils.simpleRender(sendTo, context);
        this.text = TemplateUtils.simpleRender(text, context);
        this.subject = TemplateUtils.simpleRender(subject, context);
    }
}
